<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <base-table-card>
      <template #header-left>
        <el-tabs v-model="searchParams.authStatus" @tab-change="loadGetTableData">
          <el-tab-pane label="正常" name="NORMAL" />
          <el-tab-pane label="已取消" name="CANCEL" />
        </el-tabs>
      </template>

      <template #header-right>
        <el-button type="primary" v-if="searchParams.authStatus != 'CANCEL'" @click="goToAuth">新增授权</el-button>
      </template>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <template #logoUrl="{ row }">
          <el-avatar :src="row.logoUrl" />
        </template>

        <template #authStatus="{ row }">
          <el-tag :type="row.authStatus === 'NORMAL' ? 'success' : 'info'">
            {{ row.authStatus === "NORMAL" ? "已授权" : "已取消" }}
          </el-tag>
        </template>

        <template #menu="{ row }">
          <ActionBar :row="row" :max-inline="2" :actions="buildRowActions" />
        </template>
      </avue-crud>
    </base-table-card>
    <base-dialog
      v-model="reasonVisible"
      title="查看失败原因："
      width="520px"
      :close-on-click-modal="false"
      :show-footer="false"
    >
      <div style="text-align: center">
        {{ reasonText }}
      </div>
    </base-dialog>
    <base-dialog
      v-model="logVisible"
      title="操作日志："
      width="900px"
      :close-on-click-modal="false"
      :show-footer="false"
    >
      <el-table :data="logRows">
        <el-table-column prop="idx" label="序号" width="80" />
        <el-table-column prop="time" label="操作时间" width="200" />
        <el-table-column prop="user" label="操作人员" width="120" />
        <el-table-column prop="action" label="操作内容" width="160" />
        <el-table-column prop="detail" label="详情" />
      </el-table>
    </base-dialog>
  </base-container>
</template>

<script setup>
  import useCrudHook from "avue-table/useCrudHook";
  import Option from "@/crudOption/base/channel/miniProgram.js";
  import ActionBar from "@/components/ActionBar/ActionBar.vue";
  import { createBuildMiniProgramActions } from "@/crudOption/base/channel/miniProgramAction.js";
  import { ElMessageBox } from "element-plus";

  // 定义 props
  const props = defineProps({
    type: {
      type: String,
      default: "ALIPAY", // 默认支付宝
      validator: value => ["ALIPAY", "WECHAT", "KUAISHOU"].includes(value),
    },
  });

  const emit = defineEmits(["refresh-auth-status", "go-to-auth"]);

  const reasonVisible = ref(false);
  const reasonText = ref("");

  function openReason(row) {
    reasonText.value = row.failReason || "暂无失败原因";
    reasonVisible.value = true;
  }

  const logVisible = ref(false);
  const logRows = ref([]);

  async function openLog(row) {
    try {
      const res = await Api.channel.GetLogList({ id: row.id });
      logRows.value = res.data || [];
      logVisible.value = true;
    } catch (error) {
      console.error("获取日志失败:", error);
    }
  }

  // 操作确认函数
  async function confirmFirstSubmit(row) {
    try {
      await ElMessageBox.confirm(`确定要首次提审【${row.miniName}】吗？`, "提示");
      await Api.channel.FirstSubmitVersion({ id: row.id, type: props.type });
      loadGetTableData();
    } catch {
      // 用户取消或操作失败
    }
  }

  async function confirmResubmit(row) {
    try {
      await ElMessageBox.confirm(`确定要重新提审【${row.miniName}】吗？`, "提示");
      await Api.channel.ReAuditVersion({ id: row.id, type: props.type });
      loadGetTableData();
    } catch {
      // 用户取消或操作失败
    }
  }

  async function confirmSubmit(row) {
    try {
      await ElMessageBox.confirm(`确定要提审【${row.miniName}】吗？`, "提示");
      await Api.channel.LaunchVersion({ id: row.id, type: props.type });
      loadGetTableData();
    } catch {
      // 用户取消或操作失败
    }
  }

  async function confirmRollback(row) {
    try {
      await ElMessageBox.confirm(`确定要回滚【${row.miniName}】吗？`, "提示");
      await Api.channel.RollbackVersion({ id: row.appId, type: props.type });
      loadGetTableData();
    } catch {
      // 用户取消或操作失败
    }
  }

  async function contactCustomer(row) {
    try {
      const res = await Api.channel.ContactCustomer({
        id: row.id,
        type: props.type,
      });

      if (res.code === "200" && res.data) {
        const { customerName, customerContactName, customerContactPhone } = res.data;
        const contactInfo = customerContactPhone
          ? `${customerName}（${customerContactName}）：${customerContactPhone}`
          : `${customerName}：联系电话暂未提供`;

        ElMessageBox.alert(contactInfo, "联系客户", {
          confirmButtonText: "确定",
          type: "info",
        });
      }
    } catch (error) {
      console.error("联系客户接口调用失败:", error);
    }
  }

  // 跳转到授权页面
  function goToAuth() {
    emit("go-to-auth");
  }

  // 生成操作按钮配置
  const buildRowActions = createBuildMiniProgramActions({
    fns: {
      confirmFirstSubmit,
      confirmResubmit,
      confirmSubmit,
      confirmRollback,
      openReasonDialog: openReason,
      openLogDialog: openLog,
      contactCustomer,
    },
    denyStrategy: "hide",
  });

  onMounted(() => {
    loadGetTableData();
    loadGetNewVersion();
  });

  async function loadGetNewVersion() {
    try {
      const res = await Api.channel.GetMiniProgramNewVersion({ miniType: props.type });
      console.log(res);
    } catch (error) {
      console.error("获取最新版本失败:", error);
    }
  }

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.channel.GetMiniProgramList,
    search: { miniType: props.type, authStatus: "NORMAL" },
    getParamsFormat: params => {
      // 授权时间
      if (params.authorizeTime && params.authorizeTime.length === 2) {
        params.authTimeBegin = params.authorizeTime[0];
        params.authTimeEnd = params.authorizeTime[1];
        delete params.authorizeTime;
      }
      // 提审时间
      if (params.submitTime && params.submitTime.length === 2) {
        params.auditTimeBegin = params.submitTime[0];
        params.auditTimeEnd = params.submitTime[1];
        delete params.submitTime;
      }
      // 返回查询参数
      return params;
    },
    // add: Api.customer.AddCustomer,
    // edit: Api.customer.UpdateCustomer,
  });

  // 获取 搜索配置 和 表格配置
  const { searchOption, tableOption } = Option(props.type);
</script>

<style lang="scss" scoped></style>
